package com.example.robocontroller.handler;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.UUID;

public class BluetoothDataTranslator extends Thread {
    BluetoothSocket device;
    private final OutputStream os;
    private int alpha = 90;
    private BluetoothAdapter mBluetoothAdapter;

    BluetoothDataTranslator(BluetoothDevice bd) throws IOException {
        this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        this.device = bd.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
        this.os = this.device.getOutputStream();
    }

    public void setAlphaInfo(int alpha) {
        this.alpha = alpha;
    }

    @Override

    public void run() {
        boolean success = false;
        try {
            this.device.connect();
            success = true;
        } catch (Exception e) {
            Log.d("Error connect", e.getMessage());
        }
        if (success) {
            int old_alpha = -10;
            while (true) {
                if (old_alpha != alpha) {
                    try {
                        this.os.write((alpha + "|").getBytes());
                    } catch (IOException e) {
                        Log.d("buffer", e.getMessage());
                    }
                    old_alpha = this.alpha;
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    Log.d("buffer", e.getMessage());
                }
            }
        }

    }

}
